import accountApi from "@/api/Account.js";
import tokenHelper from "@/util/logintoken";



const useUserStore =defineStore(
    'user',
    {
        state:()=>({
            token : tokenHelper.getLoginToken(),
            userMenu:[],
            userinfo:{}
        }),
        actions:{
            login(username,pwd){
                return new Promise((resolve,reject)=>{
                    accountApi.login(username,pwd).then(res=>{
                        tokenHelper.setLoginToken(res.data.data);
                        this.token = res.data.data;
                        resolve();
                    }).catch(error=>{
                         reject(error);
                        });
                });
            },
            loginOut(){
                tokenHelper.removeLoginToken();
                location.href='/login';
            },
            initLoginInfo(){
                return new Promise((resolve,reject)=>{
                    accountApi.getUserMenu().then(res=>{
                        if(res.data.success){
                            this.userMenu = res.data.data;
                            accountApi.getUserInfo().then(res=>{
                                if(res.data.success){
                                    this.userinfo = res.data.data;
                                    resolve();
                                }
                            }).catch(error=>reject(error));
                        }
                    }).catch(error=>reject(error));
                    
                });
                
            },
            getUserMenu(){
                return this.userMenu;
            }
        }
    }
);
export default useUserStore;